<?php

define('THUMB_WIDTH', 300);
define('THUMB_HEIGHT', 300);
define('THUMB_QUALITY', 85);

class ComuploadApp extends MemberbaseApp
{
    function __construct()
    {
        $this->ComuploadApp();
    }

    function ComuploadApp()
    {
		if(ACT=="newupload" || ACT=="sample_pics_upload" || ACT=="order_pics_upload")
		{
		  /* 建立会话 */
		  if (isset($_POST["ECM_ID"]) && isset($_POST['HTTP_USER_AGENT']))
		  {
			  $_COOKIE['ECM_ID'] = $_POST["ECM_ID"];
			  $_SERVER['HTTP_USER_AGENT'] = $_POST['HTTP_USER_AGENT'];
		  }
		  else
		  {
			  $this->json_error('no_post_params_authorize');
			  exit();
		  }
		}
        parent::__construct();
    }
	
	function sample_pics()
	{
		$id = empty($_GET['id']) ? 0 : intval($_GET['id']);
		$this->assign('phpsision', session_id());
		$this->assign('id', $id);
		/* 编辑器图片批量上传器 */
		$this->assign('editor_upload1', $this->_build_upload(array(
				'button_text' => Lang::get('普通上传'),
				'button_id' => 'spanButtonPlaceholder1',
				'progress_id' => 'goods_upload_progress1',
				'upload_url' => "index.php?app=comupload&act=sample_pics_upload&belongs=1000&id={$id}&upload_type=other_pic",
				'if_multirow' => 1
		)));
		$this->assign('editor_upload2', $this->_build_upload(array(
				'button_text' => Lang::get('普通上传'),
				'button_id' => 'spanButtonPlaceholder2',
				'progress_id' => 'goods_upload_progress2',
				'upload_url' => "index.php?app=comupload&act=sample_pics_upload&belongs=1000&id={$id}&upload_type=front_pic",
				'if_multirow' => 1
		)));
		$this->display('sample_pics.html');

	}

	function order_pics()
	{
		$id = empty($_GET['id']) ? 0 : intval($_GET['id']);
		if (!IS_POST) {
			$this->display('order.pic.html');
		} else {
            $front_pic = $_FILES['front_pic'];
            $other_pic = $_FILES['other_pic'];
            $dirname = $id ? 'data/files/order/' .date('Ym') : 'data/files/order/temp';
			if ($front_pic['error'] == UPLOAD_ERR_NO_FILE  && $other_pic['error'] == UPLOAD_ERR_NO_FILE) {
				echo "<script type='text/javascript'>alert('" . Lang::get('file_empty') . "');window.parent.unblock();</script>";
				return;
			} else {
				if ($front_pic['error'] == UPLOAD_ERR_OK) {
					$front_pic_path = $this->_upload_pics($front_pic, $dirname);
				}
				if ($other_pic['error'] == UPLOAD_ERR_OK) {
					$other_pic_path = $this->_upload_pics($other_pic, $dirname);
				}
				if ($id) {
					echo "<script type='text/javascript'>alert('" . Lang::get('file_upload_success') . "');window.parent.update_order_pics('" . $front_pic_path . "', '" . $other_pic_path . "');</script>";
				} else {
					echo "<script type='text/javascript'>alert('" . Lang::get('file_upload_success') . "');window.parent.update_order_pics('" . $front_pic_path . "', '" . $other_pic_path . "');</script>";
				}
			}
		}
	}
	
	function _upload_pics($file, $dirname)
	{
            import('image.func');
            import('uploader.lib');
            $uploader = new Uploader();
            $uploader->allowed_type(IMAGE_FILE_TYPE);
            $uploader->allowed_size(SIZE_IMAGE); // 2M
            $upload_mod =& m('uploadedfile');
			
                /* 处理文件上传 */
                $addfile = array(
                    'name'      => $file['name'],
                    'type'      => $file['type'],
                    'tmp_name'  => $file['tmp_name'],
                    'size'      => $file['size'],
                    'error'     => $file['error']
                );
                $uploader->addFile($addfile);
                if (!$uploader->file_info())
                {
                    $data = current($uploader->get_error());
                    $res = Lang::get($data['msg']);
                    echo "<script type='text/javascript'>alert('{$res}');window.parent.unblock();</script>";
                    exit;
                }
				
                $uploader->root_dir(ROOT_PATH);
                $filename  = $uploader->random_filename();
                $file_path = $uploader->save($dirname, $filename);
				
				return $file_path;
	}
	
	function news()
	{
		$belongs = BELONGS_NEWS;
		$id = empty($_GET['id']) ? 0 : intval($_GET['id']);
		if (!IS_POST) {
			$this->assign('belongs', $belongs);
			$this->assign('id', $id);
			$this->display('upload.html');
		} else {
			$arr_file = $_FILES['files'];
			$files = array();
			foreach ($arr_file['name'] as $key => $name) {
				$files[$key]['name'] = $arr_file['name'][$key];
				$files[$key]['type'] = $arr_file['type'][$key];
				$files[$key]['tmp_name'] = $arr_file['tmp_name'][$key];
				$files[$key]['size'] = $arr_file['size'][$key];
				$files[$key]['error'] = $arr_file['error'][$key];
			}
			
			/* 文件保存路径 */
			$dirname = '';
			if ($id!=DEFAULT_CUSTOMER_KEY_ID) {
				$dirname = 'data/files/news/' . $id;
			} else {
				$dirname = 'data/files/news/temp';
			}
			$file_path = array();
			foreach ($files as $key => $file) {
				if ($file['error'] != UPLOAD_ERR_NO_FILE) {
					$file_path[$key]['name'] = $file['name'];
					$file_path[$key]['id'] = $this->_upload_docs($belongs, $id, $file, $dirname, true);
				}
			}
			if ($file_path) {
				$upload_mod =& m('upload');
				$arr_file_path = 'new Array(';
				foreach ($file_path as $key => $path) {
					$image = $upload_mod->get_info($path['id']);
					$arr_file_path .= "new Array('$image[file_path]', '$path[id]'),";
                                        $paths[]=array('path'=>$path[name],'id'=>$path[id],'url'=>$dirname.'/'.$path[name]);
				}
				$arr_file_path = substr($arr_file_path, 0, strlen($arr_file_path) - 1) . ')';
                                if(IS_AJAX){
                                    echo "<script type='text/javascript'>";
                                    $this->json_result($paths,Lang::get('file_upload_success'));
                                    echo "</script>";
                                    exit;
                                }
				echo "<script type='text/javascript'>alert('" . Lang::get('file_upload_success') . "');window.parent.get_upload_news($arr_file_path);window.parent.unblock();</script>";
			} else {
				echo "<script type='text/javascript'>alert('" . Lang::get('file_empty') . "');window.parent.unblock();</script>";
			}
		}
	}
	
	function upload()
	{
		$belongs = empty($_GET['belongs']) ? 0 : intval($_GET['belongs']);
		$id = empty($_GET['id']) ? 0 : intval($_GET['id']);
		if (!$belongs || !$id) {
                    if(IS_AJAX){
                        $this->json_error(Lang::get('system_error'));
                        exit;
                    }
			echo "<script type='text/javascript'>alert('" . Lang::get('system_error') . "');window.parent.unblock();</script>";
			exit;
		}
		if (!IS_POST) {
			$this->assign('belongs', $belongs);
			$this->assign('phpsision', session_id());
			$this->assign('id', $id);
                        $this->assign('ajax', $_REQUEST['ajax']?'1':'');
                        $this->assign('jsoncallback', $_REQUEST['jsoncallback']?$_REQUEST['jsoncallback']:'');
						
			$this->display('upload.html');
		} else {
			$arr_file = $_FILES['files'];
			$files = array();
			foreach ($arr_file['name'] as $key => $name) {
				$files[$key]['name'] = $arr_file['name'][$key];
				$files[$key]['type'] = $arr_file['type'][$key];
				$files[$key]['tmp_name'] = $arr_file['tmp_name'][$key];
				$files[$key]['size'] = $arr_file['size'][$key];
				$files[$key]['error'] = $arr_file['error'][$key];
			}
			
			/* 文件保存路径 */
			$dirname = '';
			$upload_files_id = '';
			if ($belongs == BELONGS_SOURCING_LIST) {
				$dirname = 'data/files/sourcing/' . $id;
				$upload_file_id = 'sourcing_files';
			} elseif ($belongs == BELONGS_FACTORY) {
				$dirname = 'data/files/sample/' . $id;
				$upload_file_id = 'factory_files';
			} elseif ($belongs == BELONGS_SAMPLE_FILESIZE) {
				$dirname = 'data/files/sample/' . $id;
				$upload_file_id = 'sample_filesize';
			}elseif ($belongs == BELONGS_SAMPLE_CUSTOMER_REVIEWS) {
				$dirname = 'data/files/sample/customer/' . $id;
				$upload_file_id = 'sample_customer_filesize';
			} elseif ($belongs == BELONGS_SAMPLE_MAKEPANEL) {
				$dirname = 'data/files/sample/makepanel/' . $id;
				$upload_file_id = 'sample_makepanel_filesize';
			}elseif ($belongs == BELONGS_CONSUMER_REVIEWS){
				$dirname = 'data/files/sample/consumer_reviews/' . $id;
				$upload_file_id = 'sample_consumer_reviews';
			}elseif ($belongs == BELONGS_CONSUMER_REMARK){
				$dirname = 'data/files/sample/consumer_remark/' . $id;
				$upload_file_id = 'sample_consumer_remark';
			}elseif ($belongs == BELONGS_ORDER) {
				$dirname = 'data/files/order/' . $id;
				$upload_file_id = 'order_files';
			}elseif ($belongs == BELONGS_ORDER_QC_REPORT) {
				$dirname = 'data/files/order/' . $id;
				$upload_file_id = 'qcreport_files';
			}elseif ($belongs == BELONGS_ORDER_DIS_REASON) {
				$dirname = 'data/files/order/disreason/' . $id;
				$upload_file_id = 'disreason_files';
			}elseif ($belongs == BELONGS_ORDER_BEIZHU) {
				$dirname = 'data/files/order/beizhu/' . $id;
				$upload_file_id = 'beizhu_files';
			} elseif ($belongs == BELONGS_NEWSFILE) {
				$dirname = 'data/files/news/' . $id;
				$upload_file_id = 'news_files';
			} elseif ($belongs == BELONGS_COLORCARD) {
				$dirname = 'data/files/sample/' . $id;
				$upload_file_id = 'color_card';
			} elseif ($belongs == BELONGS_PIGAI) {
				$dirname = 'data/files/order/' .date('Ym');
				$upload_file_id = 'file_pigai';
			} elseif ($belongs == BELONGS_HETONG) {
				$dirname = 'data/files/order/' .date('Ym');
				$upload_file_id = 'file_hetong';
			} elseif ($belongs == BELONGS_ZHIDAN) {
				$dirname = 'data/files/order/' .date('Ym');
				$upload_file_id = 'file_zhidan';
			} elseif ($belongs == BELONGS_CHAHUO) {
				$dirname = 'data/files/order/' .date('Ym');
				$upload_file_id = 'file_chahuo';
			} elseif ($belongs == BELONGS_KOUKUAN) {
				$dirname = 'data/files/order/' .date('Ym');
				$upload_file_id = 'file_koukuan';
			} elseif ($belongs == BELONGS_DANBAO) {
				$dirname = 'data/files/order/' .date('Ym');
				$upload_file_id = 'file_danbao';
			} elseif ($belongs == BELONGS_SOURCING_INVOICES) {
				$dirname = 'data/files/sample/sourcing/' .date('Ym');
				$upload_file_id = 'sample_sourcing';
			} elseif ($belongs == BELONGS_ORDER_SOURCING_INVOICES) {
				$dirname = 'data/files/order/sourcing/' .date('Ym');
				$upload_file_id = 'sample_sourcing';
			} elseif ($belongs == BELONGS_BULK_INVOICES) {
				$dirname = 'data/files/order/bulk/' .date('Ym');
				$upload_file_id = 'sample_sourcing';
			} elseif ($belongs == BELONGS_CONSUMER_COMMENT_ORDER){
				$dirname = 'data/files/order/consumer/' .date('Ym');
				$upload_file_id = 'file_consumer_comment';
			} elseif ($belongs == BELONGS_CONSUMER_REMARKS_ORDER){
				$dirname = 'data/files/order/consumer/' .date('Ym');
				$upload_file_id = 'file_consumer_remarks';
			} elseif ($belongs == BELONGS_QUOTE_ORDER){
				$dirname = 'data/files/order/quote/' .date('Ym');
				$upload_file_id = 'quote_order_file';
			} elseif ($belongs == BELONGS_SAMPLE_THUMB_IMG){
				$dirname='data/files/sample/thumb/' .date('Ym');
				$upload_file_id='sample_thumb_img';
			} elseif ($belongs == BELONGS_RECEIPT_ORDER){
				$dirname='data/files/order/receipt/' .date('Ym');
				$upload_file_id='receipt_order_file';
			}elseif ($belongs == BELONGS_QUOTE_CONTRACT){
				$dirname = 'data/files/order/quote/contract/' .date('Ym');
				$upload_file_id = 'quote_contract_file';
			}elseif ($belongs == BELONGS_CUT_ORDER){
				$dirname = 'data/files/order/cut/' .date('Ym');
				$upload_file_id = 'cut_order_file';
			}elseif ($belongs == BELONGS_FABRIC_INFO){
				$dirname = 'data/files/sample/fabric/' .date('Ym');
				$upload_file_id = 'fabric_info_file';
			}elseif ($belongs == BELONGS_SAMPLE_PATTERN){
				$dirname = 'data/files/sample/pattern/' .date('Ym');
				$upload_file_id = 'sample_pattern_file';
			}elseif ($belongs == BELONGS_PROCESS_RECEIPT){
				$dirname = 'data/files/order/process/' .date('Ym');
				$upload_file_id = 'process_receipt_file';
			}elseif ($belongs==BELONGS_MAIN_LABEL){
				$dirname = 'data/files/order/main/' .date('Ym');
				$upload_file_id = 'main_label_file';
			}elseif ($belongs==BELONGS_QUOTE_DETAIL){
				$dirname = 'data/files/order/quote/info/' .date('Ym');
				$upload_file_id = 'factory_quote_info';
			}elseif ($belongs==BELONGS_QUOTE_THUM_IMG){
				$dirname = 'data/files/order/quote/thumb/' .date('Ym');
				$upload_file_id = 'quote_thumb_img';
			}elseif ($belongs==BELONGS_SAMPLE_QUOTE_DETAIL){
				$dirname = 'data/files/sample/quote/info/' .date('Ym');
				$upload_file_id = 'factory_quote_info';
			}elseif ($belongs==BELONGS_SAMPLE_QUOTE_THUM_IMG){
				$dirname = 'data/files/sample/quote/thumb/' .date('Ym');
				$upload_file_id = 'quote_thumb_img';
			}elseif ($belongs==BELONGS_NEWS){
				$dirname = 'data/files/news/' .date('Ym');
				$upload_file_id = 'news_images';
			}elseif ($belongs==BELONGS_LISTING_IMG){
				$dirname = 'data/files/order/listing/' .date('Ym');
				$upload_file_id = 'listing_img';
			}elseif ($belongs==BELONGS_STATEMENT_FILE){
				$dirname = 'data/files/order/statement/' .date('Ym');
				$upload_file_id = 'statement_file_'.$id;
			}elseif ($belongs==BELONGS_MEMBER_IMG){
				$dirname = 'data/files/member/' .date('Ym');
				$upload_file_id = 'member_beautiful_img';
			}elseif ($belongs==BELONGS_ORDER_THUMB_IMG){
				$dirname = 'data/files/order/thumb/' .date('Ym');
				$upload_file_id = 'order_thumb_image';
			}elseif ($belongs==BELONGS_CONSUMER_SCHEDULE){
				$dirname = 'data/files/consumer/schedule/' .date('Ym');
				$upload_file_id = 'consumer_schedule_file';
			}elseif ($belongs==BELONGS_SAMPLE_REF_IMG){
				$dirname = 'data/files/sample/ref/' .date('Ym');
				$upload_file_id = 'ref_img';
			}elseif ($belongs==BELONGS_SAMPLE_RECOMM_COLOR){
				$dirname = 'data/files/sample/recomm/' .date('Ym');
				$upload_file_id = 'demand_recomm_file';
			}elseif ($belongs==BELONGS_ORDER_REF_IMG){
				$dirname = 'data/files/order/ref/' .date('Ym');
				$upload_file_id = 'ref_img';
			}elseif ($belongs==BELONGS_ORDER_RECOMM_COLOR){
				$dirname = 'data/files/order/recomm/' .date('Ym');
				$upload_file_id = 'demand_recomm_file';
			}elseif ($belongs==BELONGS_SS_WATER_IMG){
				$dirname='data/files/order/ss/water/'.date('Ym');
				$upload_file_id='ss_water_img';
			}
			else{
				$dirname = 'data/files/order/' .date('Ym');
				$upload_file_id = 'order_attachment';
			}
			$file_path = array();
			foreach ($files as $key => $file) {
				if ($file['error'] != UPLOAD_ERR_NO_FILE) {
					$file_path[$key]['name'] = $file['name'];
					$file_path[$key]['id'] = $this->_upload_docs($belongs, $id, $file, $dirname);
				}
			}
			if ($file_path) {
				$arr_file_path = 'new Array(';
				foreach ($file_path as $path) {
					$arr_file_path .= "new Array('$path[name]', '$path[id]'),";
                                        $paths[]=array('path'=>$path[name],'id'=>$path[id],'url'=>$dirname.'/'.$path[name]);
				}
				$arr_file_path = substr($arr_file_path, 0, strlen($arr_file_path) - 1) . ')';
                                if(IS_AJAX){
                                    echo "<script type='text/javascript'>";
                                    $this->json_result($paths,Lang::get('file_upload_success'));
                                    echo "</script>";
                                    exit;
                                }
				echo "<script type='text/javascript'>alert('" . Lang::get('file_upload_success') . "');window.parent.get_upload_files('$upload_file_id', $arr_file_path);window.parent.unblock();</script>";
			} else {
				echo "<script type='text/javascript'>alert('" . Lang::get('file_empty') . "');window.parent.unblock();</script>";
			}
		}
	}
	
	function _upload_docs($belongs, $id, $file, $dirname, $is_img = false)
	{
            import('image.func');
            import('uploader.lib');
            $uploader = new Uploader();
            $is_img ? $uploader->allowed_type(IMAGE_FILE_TYPE) : $uploader->allowed_type(DOC_FILE_TYPE);
            $uploader->allowed_size(SIZE_DOC); // 5M
            $upload_mod =& m('uploadedfile');
			
                /* 处理文件上传 */
                $addfile = array(
                    'name'      => $file['name'],
                    'type'      => $file['type'],
                    'tmp_name'  => $file['tmp_name'],
                    'size'      => $file['size'],
                    'error'     => $file['error']
                );
                $uploader->addFile($addfile);
                if (!$uploader->file_info())
                {
                    $data = current($uploader->get_error());
                    $res = Lang::get($data['msg']);
                    echo "<script type='text/javascript'>alert('{$res}');window.parent.unblock();</script>";
                    exit;
                }
				
                $uploader->root_dir(ROOT_PATH);
                $filename  = $uploader->random_filename();
                $file_path = $uploader->save($dirname, $filename);
				
				/* 将文件信息写入数据库 */
				$upload_mod =& m('upload');
				$data = array(
					'file_name' => $addfile['name'],
					'file_path' => $file_path,
					'file_type' => $belongs,
					'key_id' => $id
				);
				if ($this->visitor->get('role')==USER_MERCHANT){
					$data['merch_id']=$this->visitor->get('user_id');
				}
				$file_id = $upload_mod->add($data);
				
				return $file_id;
	}
	
	function delete()
	{
		$id = empty($_GET['id']) ? 0 : intval($_GET['id']);
		if (!$id) {
			if ($_GET['ajax']) {
				echo ecm_json_encode(array('done'=>'false','msg'=>Lang::get('file_not_exist')));
			} else {
				$this->show_warning('file_not_exist');
			}
			return;
		}
		
		$upload_mod =& m('upload');
		$file = $upload_mod->get_info($id);
		if (!$file) {
			if ($_GET['ajax']) {
				echo ecm_json_encode(array('done'=>'false','msg'=>Lang::get('file_not_exist')));
			} else {
				$this->show_warning('file_not_exist');
			}
			return;
		}
		
		if (!$upload_mod->drop($id)) {
			if ($_GET['ajax']) {
				echo ecm_json_encode(array('done'=>'false','msg'=>Lang::get('drop_file_defeated')));
			} else {
				$this->show_warning('drop_file_defeated');
			}
			return;
		} else {
			if (file_exists($file['file_path'])) {
				unlink($file['file_path']);
			} else {
				if ($_GET['ajax']) {
					echo ecm_json_encode(array('done'=>'false','msg'=>Lang::get('file_defeated')));
				} else {
					$this->show_warning('file_defeated');
				}
				return;
			}
		}
		if ($_GET['ajax']) {
			/*echo 'true';*/
			echo ecm_json_encode(array('done'=>'true','msg'=>Lang::get('drop_file_success')));
			return;
		}
		$this->show_message('drop_file_success');
	}

	//设为首页
	function default_image(){
		$id = empty($_GET['id']) ? 0 : intval($_GET['id']);
		$cc_id = empty($_GET['cc_id']) ? 0 : intval($_GET['cc_id']);
		$result=array();
		if (!$id && !$cc_id) {
			if ($_GET['ajax']) {
				$result=array('done'=>'false','msg'=>Lang::get('file_not_exist'));
				exit(ecm_json_encode($result));
			} else {
				$this->show_warning('file_not_exist');
			}
			return;
		}
		
		$upload_mod =& m('upload');
		$colorcard_mod=&m('color_card');
		$file = $upload_mod->get_info($id);
		if (empty($file)) {
			if ($_GET['ajax']) {
				$result=array('done'=>'false','msg'=>Lang::get('file_not_exist'));
				exit(ecm_json_encode($result));
			} else {
				$this->show_warning('file_not_exist');
			}
			return;
		}
		
		if (!$colorcard_mod->edit($cc_id,array('default_image'=>$file['file_path']))) {
			if ($_GET['ajax']) {
				$result=array('done'=>'false','msg'=>Lang::get('setting_error'));
				exit(ecm_json_encode($result));
			} else {
				$this->show_warning('setting_error');
			}
			return;
		} 
		if ($_GET['ajax']) {
			$result=array('done'=>'true','msg'=>Lang::get('setting_success'));
		}
		exit(ecm_json_encode($result));
	}
	
	
    function view_iframe()
    {
		$belong = empty($_GET['belong']) ? -1 : intval($_GET['belong']);
		if ($belong == -1) {
			echo "<script type='text/javascript'>alert('" . Lang::get('system_error') . "');window.parent.unblock();</script>";
			return;
		}
		
		$id = empty($_GET['id']) ? 0 : intval($_GET['id']);
		
		$this->assign('belong', $belong);
        $this->display("comupload.html");
    }

    function uploadedfile()
    {
            import('image.func');
            import('uploader.lib');
            $uploader = new Uploader();
            $uploader->allowed_type(IMAGE_FILE_TYPE);
            $uploader->allowed_size(SIZE_IMAGE); // 2M
            $upload_mod =& m('uploadedfile');
            /* 取得剩余空间（单位：字节），false表示不限制 
            $store_mod  =& m('store');
            $settings   = $store_mod->get_settings($this->store_id);

            $remain     = $settings['space_limit'] > 0 ? $settings['space_limit'] * 1024 * 1024 - $upload_mod->get_file_size($this->store_id) : false;*/

            $files = $_FILES['file1'];
			
            if ($files['error'] === UPLOAD_ERR_OK)
            {
                /* 处理文件上传 */
                $file = array(
                    'name'      => $files['name'],
                    'type'      => $files['type'],
                    'tmp_name'  => $files['tmp_name'],
                    'size'      => $files['size'],
                    'error'     => $files['error']
                );
                $uploader->addFile($file);
                if (!$uploader->file_info())
                {
                    $data = current($uploader->get_error());
                    $res = Lang::get($data['msg']);
                    $this->view_iframe();
                    echo "<script type='text/javascript'>alert('{$res}');</script>";
                    return false;
                }
                /* 判断能否上传 */
                if ($remain !== false)
                {
                    if ($remain < $file['size'])
                    {
                        $res = Lang::get('space_limit_arrived');
                        $this->view_iframe();
                        echo "<script type='text/javascript'>alert('{$res}');</script>";
                        return false;
                    }
                }

                $uploader->root_dir(ROOT_PATH);
                $dirname = '';
                if ($this->belong == BELONG_GOODS)
                {
                    $dirname = 'data/files/store_' . $this->visitor->get('manage_store') . '/goods_' . (time() % 200);
                }
                elseif ($this->belong == BELONG_STORE)
                {
                    $dirname = 'data/files/store_' . $this->visitor->get('manage_store') . '/other';
                }
                elseif ($this->belong == BELONG_ARTICLE)
                {
                    $dirname = 'data/files/store_' . $this->visitor->get('manage_store').'/article';
                }

                $filename  = $uploader->random_filename();
                $file_path = $uploader->save($dirname, $filename);
                /* 处理文件入库 */
                $data = array(
                    'store_id'  => $this->store_id,
                    'file_type' => $file['type'],
                    'file_size' => $file['size'],
                    'file_name' => $file['name'],
                    'file_path' => $file_path,
                    'belong'    => $this->belong,
                    'item_id'   => $this->id,
                    'add_time'  => gmtime(),
                );
                $file_id = $upload_mod->add($data);
                if (!$file_id)
                {
                    $this->_error($uf_mod->get_error());
                    return false;
                }

                if ($this->instance == 'goods_image') // 如果是上传商品相册图片
                {
                    /* 生成缩略图 */
                    $thumbnail = dirname($file_path) . '/small_' . basename($file_path);
                    make_thumb(ROOT_PATH . '/' . $file_path, ROOT_PATH .'/' . $thumbnail, THUMB_WIDTH, THUMB_HEIGHT, THUMB_QUALITY);

                    /* 更新商品相册 */
                    $mod_goods_image = &m('goodsimage');
                    $goods_image = array(
                        'goods_id'   => $this->id,
                        'image_url'  => $file_path,
                        'thumbnail'  => $thumbnail,
                        'sort_order' => 255,
                        'file_id'    => $file_id,
                    );
                    if (!$mod_goods_image->add($goods_image))
                    {
                        $this->_error($this->mod_goods_imaged->get_error());
                        return false;
                    }
                    $data['thumbnail'] = $thumbnail;

                }

                $data['instance'] = $this->instance;
                $data['file_id'] = $file_id;
                $res = "{";
                foreach ($data as $key => $val)
                {
                    $res .= "\"$key\":\"$val\",";
                }
                $res = substr($res, 0, strrpos($res, ','));
                $res .= '}';
                $this->view_iframe();
                echo "<script type='text/javascript'>window.parent.add_uploadedfile($res);</script>";
            }
            elseif ($files['error'] == UPLOAD_ERR_NO_FILE)
            {
                $res = Lang::get('file_empty');
                $this->view_iframe();
                echo "<script type='text/javascript'>alert('{$res}');</script>";
                return false;
            }
            else
            {
                $res = Lang::get('sys_error');
                $this->view_iframe();
                echo "<script type='text/javascript'>alert('{$res}');</script>";
                return false;
            }

    }

    function view_remote()
    {
        $this->assign("act", 'remote_image');
        $this->assign("instance", $this->instance);
        $this->assign("id", $this->id);
        $this->assign("belong", $this->belong);
        $this->display("image.html");
    }

    function remote_image()
    {
        import('image.func');
        import('uploader.lib');
        $uploader = new Uploader();
        $uploader->allowed_type(IMAGE_FILE_TYPE);
        $uploader->allowed_size(SIZE_GOODS_IMAGE); // 2M
        $upload_mod =& m('uploadedfile');
        /* 取得剩余空间（单位：字节），false表示不限制 */
        $store_mod  =& m('store');
        $settings   = $store_mod->get_settings($this->store_id);
        $remain     = $settings['space_limit'] > 0 ? $settings['space_limit'] * 1024 * 1024 - $upload_mod->get_file_size($this->store_id) : false;
        $uploader->root_dir(ROOT_PATH);
        $dirname = '';
        $remote_url = trim($_POST['remote_url']);
        if (!empty($remote_url))
        {
            if(preg_match("/^(http:\/\/){1,1}.+(gif|png|jpeg|jpg){1,1}$/i", $remote_url))
            {
                $result = $this->url_exist($remote_url, 2097152, $remain);
                if ($result === 1)
                {
                    $this->view_remote();
                    $res = Lang::get("url_invalid");
                    echo "<script type='text/javascript'>alert('{$res}');</script>";
                    return false;
                }
                elseif ($result === 2)
                {
                    $this->view_remote();
                    $res = Lang::get("not_allowed_size");
                    echo "<script type='text/javascript'>alert('{$res}');</script>";
                    return false;
                }
                elseif ($result === 3)
                {
                    $this->view_remote();
                    $res = Lang::get("space_limit_arrived");
                    echo "<script type='text/javascript'>alert('{$res}');</script>";
                    return false;
                }
                $img_url = _at('file_get_contents', $remote_url);
                $dirname = '';
                if ($this->belong == BELONG_GOODS)
                {
                    $dirname = 'data/files/store_' . $this->visitor->get('manage_store') . '/goods_' . (time() % 200);
                }
                elseif ($this->belong == BELONG_STORE)
                {
                    $dirname = 'data/files/store_' . $this->visitor->get('manage_store') . '/other';
                }
                elseif ($this->belong == BELONG_ARTICLE)
                {
                    $dirname = 'data/files/store_' . $this->visitor->get('manage_store').'/article';
                }
                $filename  = $uploader->random_filename();
                $new_url = $dirname . '/' . $filename . '.' . substr($remote_url, strrpos($remote_url, '.')+1);
                ecm_mkdir(ROOT_PATH . '/' . $dirname);
                $fp = _at('fopen', ROOT_PATH . '/' . $new_url, "w");
                _at('fwrite', $fp, $img_url);
                _at('fclose', $fp);
                if(!file_exists(ROOT_PATH . '/' . $new_url))
                {
                    $this->view_remote();
                    $res = Lang::get("system_error");
                    echo "<script type='text/javascript'>alert('{$res}');</script>";
                    return false;
                }
                /* 处理文件入库 */
                $data = array(
                    'store_id'  => $this->store_id,
                    'file_type' => $this->_return_mimetype(ROOT_PATH . '/' . $new_url),
                    'file_size' => filesize(ROOT_PATH . '/' . $new_url),
                    'file_name' => substr($remote_url, strrpos($remote_url, '/')+1),
                    'file_path' => $new_url,
                    'belong'    => $this->belong,
                    'item_id'   => $this->id,
                    'add_time'  => gmtime(),
                );
                $file_id = $upload_mod->add($data);
                if (!$file_id)
                {
                    $this->_error($uf_mod->get_error());
                    return false;
                }

                if ($this->instance == 'goods_image') // 如果是上传商品相册图片
                {
                    /* 生成缩略图 */
                    $thumbnail = dirname($new_url) . '/small_' . basename($new_url);
                    make_thumb(ROOT_PATH . '/' . $new_url, ROOT_PATH .'/' . $thumbnail, THUMB_WIDTH, THUMB_HEIGHT, THUMB_QUALITY);

                    /* 更新商品相册 */
                    $mod_goods_image = &m('goodsimage');
                    $goods_image = array(
                        'goods_id'   => $this->id,
                        'image_url'  => $new_url,
                        'thumbnail'  => $thumbnail,
                        'sort_order' => 255,
                        'file_id'    => $file_id,
                    );
                    if (!$mod_goods_image->add($goods_image))
                    {
                        $this->_error($this->mod_goods_imaged->get_error());
                        return false;
                    }
                    $data['thumbnail'] = $thumbnail;

                }

                $data['instance'] = $this->instance;
                $data['file_id'] = $file_id;
                $res = "{";
                foreach ($data as $key => $val)
                {
                    $res .= "\"$key\":\"$val\",";
                }
                $res = substr($res, 0, strrpos($res, ','));
                $res .= '}';
                $this->view_remote();
                echo "<script type='text/javascript'>window.parent.add_uploadedfile($res);</script>";
            }
            else
            {
               $res = Lang::get('url_invalid');
               $this->view_remote();

               echo "<script type='text/javascript'>alert('{$res}');</script>";
               return false;
            }
        }
        else
        {
            $res = Lang::get('remote_empty');
            $this->view_remote();
            echo "<script type='text/javascript'>alert('{$res}');</script>";
            return false;
        }
    }

    /**
     * 检查远程地址是否有效，文件是否超过最大允许值，剩余空间是否够用
     * @author cheng
     * @param string $url | 远程地址
     * @param int $allow_size | 允许上传文件的最大值
     * @param int $remain | 用户剩余的空间
     *            0 | 不用检查，无限大
     * @return int 1 | 无效的远程地址
     *         int 2 | 文件大小超过允许值
     *         int 3 | 文件大小超过剩余空间的大小
     *         boolen true | 通过检测
     */
    function url_exist($url, $allow_size , $remain)
    {
        if(!function_exists('get_headers'))
        {
            function get_headers($url,$format=0)
            {
                $url=parse_url($url);
                $end = "\r\n\r\n";
                $fp = fsockopen($url['host'], (empty($url['port'])?80:$url['port']), $errno, $errstr, 30);
                if ($fp)
                {
                    $out  = "GET ".$url['path']." HTTP/1.1\r\n";
                    $out .= "Host: ".$url['host']."\r\n";
                    $out .= "Connection: Close\r\n\r\n";
                    $var  = '';
                    fwrite($fp, $out);
                    while (!feof($fp))
                    {
                        $var.=fgets($fp, 1280);
                        if(strpos($var,$end))
                            break;
                    }
                    fclose($fp);

                    $var=preg_replace("/\r\n\r\n.*\$/",'',$var);
                    $var=explode("\r\n",$var);
                    if($format)
                    {
                        foreach($var as $i)
                        {
                            if(preg_match('/^([a-zA-Z -]+): +(.*)$/',$i,$parts))
                                $v[$parts[1]]=$parts[2];
                        }
                        return $v;
                    }
                    else
                        return $var;
                }
            }
        }
        $head = get_headers($url);
        if(is_array($head) && !empty($head))
        {
            foreach ($head as $key => $val)
            {
                //$val = str_replace("\r\n", '', $val);
                $pos = strpos($val, 'Content-Length');
                if($key == 0)
                {
                    $hhttp = explode(' ', $val);
                    $hsize = count($hhttp) - 1;
                    $res = strcmp($hhttp[$hsize], "OK");
                    if ($res != 0)
                    {
                        return 1;
                    }
                }
                elseif ( $pos === false)
                {
                    continue;
                }
                elseif ($pos >= 0)
                {
                    $size = explode(' ', $val);
                    $count = count($size);
                    $count = $count - 1;
                    $res = intval($size[$count]);
                    if ($res > $allow_size)
                    {
                        return 2;
                    }
                    if (!empty($remain) && $res > $remain)
                    {
                        return 3;
                    }
                }
            }
        }
        else
        {
           return 1;
        }
           return true;
    }

    function _return_mimetype($filename)
    {
        preg_match("|\.([a-z0-9]{2,4})$|i", $filename, $fileSuffix);
        switch(strtolower($fileSuffix[1]))
        {
            case "js" :
                return "application/x-javascript";

            case "json" :
                return "application/json";

            case "jpg" :
            case "jpeg" :
            case "jpe" :
                return "image/jpeg";

            case "png" :
            case "gif" :
            case "bmp" :
            case "tiff" :
                return "image/".strtolower($fileSuffix[1]);

            case "css" :
                return "text/css";

            case "xml" :
                return "application/xml";

            case "doc" :
            case "docx" :
                return "application/msword";

            case "xls" :
            case "xlsx" :
            case "xlt" :
            case "xlm" :
            case "xld" :
            case "xla" :
            case "xlc" :
            case "xlw" :
            case "xll" :
                return "application/vnd.ms-excel";

            case "ppt" :
            case "pps" :
                return "application/vnd.ms-powerpoint";

            case "rtf" :
                return "application/rtf";

            case "pdf" :
                return "application/pdf";

            case "html" :
            case "htm" :
            case "php" :
                return "text/html";

            case "txt" :
                return "text/plain";

            case "mpeg" :
            case "mpg" :
            case "mpe" :
                return "video/mpeg";

            case "mp3" :
                return "audio/mpeg3";

            case "wav" :
                return "audio/wav";

            case "aiff" :
            case "aif" :
                return "audio/aiff";

            case "avi" :
                return "video/msvideo";

            case "wmv" :
                return "video/x-ms-wmv";

            case "mov" :
                return "video/quicktime";

            case "rar" :
                return "application/x-rar-compressed";

            case "zip" :
            return "application/zip";

            case "tar" :
                return "application/x-tar";

            case "swf" :
                return "application/x-shockwave-flash";

            default :
            if(function_exists("mime_content_type"))
            {
                $fileSuffix = mime_content_type($filename);
            }
            return "unknown/" . trim($fileSuffix[0], ".");
        }
    }
	
	function _get_upload_dir($belongs = 0)
	{
		$setting = $this->_get_upload_setting();
		if (!$belongs) {
			return $setting['root_dir'];
		}
		$root_dir = $setting['root_dir'];
		$dir = '';
		switch ($belongs) {
			case FILE_SAMPLE_IMG:
				$dir = $setting['sample']['img'];
				break;
			case FILE_SAMPLE_COLORCARD:
				$dir = $setting['sample']['color_card'];
				break;
			case FILE_SAMPLE_FACTORY:
				$dir = $setting['sample']['factory'];
				break;
			case FILE_ORDER_IMG:
				$dir = $setting['order']['img'];
				break;
			case FILE_ORDER_FABRIC:
				$dir = $setting['order']['fabric'];
				break;
			case FILE_ORDER_PIGAI:
				$dir = $setting['order']['pigai'];
				break;
			case FILE_ORDER_HETONG:
				$dir = $setting['order']['hetong'];
				break;
			case FILE_ORDER_ZHIDAN:
				$dir = $setting['order']['zhidan'];
				break;
			case FILE_ORDER_CHAHUO:
				$dir = $setting['order']['chahuo'];
				break;
			case FILE_ORDER_KOUKUAN:
				$dir = $setting['order']['koukuan'];
				break;
			case FILE_OTHER_NEWS_IMG:
				$dir = $setting['other']['news_img'];
				break;
			case FILE_OTHER_NEWS_FILE:
				$dir = $setting['other']['news_files'];
				break;
		}
		$return = $root_dir . $dir;
		$last =  substr($return, strlen($return) - 2);
		if ($last == DIRECTORY_SEPARATOR) {
			$return = substr($return, -1);
		}
		return $return;
	}
	
	function customer_reviews()
	{
		$id = empty($_GET['id']) ? 0 : intval($_GET['id']);
		if (!IS_POST) {
			$this->display('sample_customer_reviews.html');
		} else {
            $customer_reviews = $_FILES['customer_reviews'];
			/* new codes 
			if ($id) {
				$dirname = $this->_get_upload_dir(FILE_SAMPLE_IMG);
				$sample_mod =& m('sample');
				$sample = $sample_mod->get_info($id);
				if (strstr($dirname, '{sample_sn}')) {
					$samples = $sample_mod->find(array(
						'conditions' => "sample_id < $id AND sample_sn = '$sample[sample_sn]'",
					));
					if (count($samples)) {
						$sample['sample_sn'] .= '-' . count($samples);
					}
				}
				$dirname = str_replace(array('{sample_id}', '{sample_sn}', '{arrival_date}', '{year}', '{month}', '{day}'), array($sample['sample_id'], $sample['sample_sn'], date('Y-m-d', $sample['arrival_date']), date('Y'), date('m'), date('d')), $dirname);
			} else {
            	$dirname = 'data/files/sample/temp';
			}*/
            /* old codes
			*/
			$dirname = $id ? 'data/files/sample/' . $id : 'data/files/sample/temp';
			if ($customer_reviews['error'] == UPLOAD_ERR_NO_FILE) {
				echo "<script type='text/javascript'>alert('" . Lang::get('file_empty') . "');window.parent.unblock();</script>";
				return;
			} else {
				if ($customer_reviews['error'] == UPLOAD_ERR_OK) {
					$customer_reviews_path = $this->_upload_customer_reviews($customer_reviews, $dirname);
				}

				if ($id) {
					echo "<script type='text/javascript'>alert('" . Lang::get('file_upload_success') . "');window.parent.update_customer_block('" . $customer_reviews_path . "');</script>";
				} else {
					echo "<script type='text/javascript'>alert('" . Lang::get('file_upload_success') . "');window.parent.get_customer_pics('" . $customer_reviews_path . "');</script>";
				}
			}
		}
	}
	
	function _upload_customer_reviews($file, $dirname)
	{
            import('image.func');
            import('uploader.lib');
            $uploader = new Uploader();
            $uploader->allowed_type(DOC_FILE_TYPE);
            $uploader->allowed_size(SIZE_IMAGE); // 2M
            $upload_mod =& m('uploadedfile');
			
                /* 处理文件上传 */
                $addfile = array(
                    'name'      => $file['name'],
                    'type'      => $file['type'],
                    'tmp_name'  => $file['tmp_name'],
                    'size'      => $file['size'],
                    'error'     => $file['error']
                );
                $uploader->addFile($addfile);
                if (!$uploader->file_info())
                {
                    $data = current($uploader->get_error());
                    $res = Lang::get($data['msg']);
                    echo "<script type='text/javascript'>alert('{$res}');window.parent.unblock();</script>";
                    exit;
                }
				
                $uploader->root_dir(ROOT_PATH);
                $filename  = $uploader->random_filename();
                $file_path = $uploader->save($dirname, $filename);
				
				return $file_path;
	}
	
	//swf上传
	function newupload()
    {
		$belongs = empty($_GET['belongs']) ? 0 : intval($_GET['belongs']);
		$id = empty($_GET['id']) ? 0 : intval($_GET['id']);
		
		if (!$belongs || !$id) {
			$this->json_error(Lang::get('system_error'));
            exit();
		}

        $ret_info = array(); // 返回到客户端的信息
        $file = $_FILES['Filedata'];
        if ($file['error'] == UPLOAD_ERR_NO_FILE) // 没有文件被上传
        {
            $this->json_error('no_upload_file');
            exit();
        }
		/* 文件保存路径 */
		$dirname = '';
		$upload_files_id = '';
		if ($belongs == BELONGS_SOURCING_LIST) {
			$dirname = 'data/files/sourcing/' . $id;
			$upload_file_id = 'sourcing_files';
		} elseif ($belongs == BELONGS_FACTORY) {
			$dirname = 'data/files/sample/' . $id;
			$upload_file_id = 'factory_files';
		} elseif ($belongs == BELONGS_SAMPLE_FILESIZE) {
			$dirname = 'data/files/sample/' . $id;
			$upload_file_id = 'sample_filesize';
		}elseif ($belongs == BELONGS_SAMPLE_CUSTOMER_REVIEWS) {
			$dirname = 'data/files/sample/customer/' . $id;
			$upload_file_id = 'sample_customer_filesize';
		} elseif ($belongs == BELONGS_SAMPLE_MAKEPANEL) {
			$dirname = 'data/files/sample/makepanel/' . $id;
			$upload_file_id = 'sample_makepanel_filesize';
		}elseif ($belongs == BELONGS_CONSUMER_REVIEWS){
			$dirname = 'data/files/sample/consumer_reviews/' . $id;
			$upload_file_id = 'sample_consumer_reviews';
		}elseif ($belongs == BELONGS_CONSUMER_REMARK){
			$dirname = 'data/files/sample/consumer_remark/' . $id;
			$upload_file_id = 'sample_consumer_remark';
		}elseif ($belongs == BELONGS_ORDER) {
			$dirname = 'data/files/order/' . $id;
			$upload_file_id = 'order_files';
		}elseif ($belongs == BELONGS_ORDER_QC_REPORT) {
			$dirname = 'data/files/order/' . $id;
			$upload_file_id = 'qcreport_files';
		}elseif ($belongs == BELONGS_ORDER_DIS_REASON) {
			$dirname = 'data/files/order/disreason/' . $id;
			$upload_file_id = 'disreason_files';
		}elseif ($belongs == BELONGS_ORDER_BEIZHU) {
			$dirname = 'data/files/order/beizhu/' . $id;
			$upload_file_id = 'beizhu_files';
		} elseif ($belongs == BELONGS_NEWSFILE) {
			$dirname = 'data/files/news/' . $id;
			$upload_file_id = 'news_files';
		} elseif ($belongs == BELONGS_COLORCARD) {
			$dirname = 'data/files/sample/' . $id;
			$upload_file_id = 'color_card';
		} elseif ($belongs == BELONGS_PIGAI) {
			$dirname = 'data/files/order/' .date('Ym');
			$upload_file_id = 'file_pigai';
		} elseif ($belongs == BELONGS_HETONG) {
			$dirname = 'data/files/order/' .date('Ym');
			$upload_file_id = 'file_hetong';
		} elseif ($belongs == BELONGS_ZHIDAN) {
			$dirname = 'data/files/order/' .date('Ym');
			$upload_file_id = 'file_zhidan';
		} elseif ($belongs == BELONGS_CHAHUO) {
			$dirname = 'data/files/order/' .date('Ym');
			$upload_file_id = 'file_chahuo';
		} elseif ($belongs == BELONGS_KOUKUAN) {
			$dirname = 'data/files/order/' .date('Ym');
			$upload_file_id = 'file_koukuan';
		} elseif ($belongs == BELONGS_DANBAO) {
			$dirname = 'data/files/order/' .date('Ym');
			$upload_file_id = 'file_danbao';
		} elseif ($belongs == BELONGS_FACTORY_IMAGE){
			$dirname = 'data/files/factory/' .date('Ym');
			$upload_file_id = 'file_factory_image';
		}elseif ($belongs == BELONGS_SOURCING_INVOICES) {
			$dirname = 'data/files/sample/sourcing/' .date('Ym');
			$upload_file_id = 'sample_sourcing';
		} elseif ($belongs == BELONGS_ORDER_SOURCING_INVOICES) {
			$dirname = 'data/files/order/sourcing/' .date('Ym');
			$upload_file_id = 'sample_sourcing';
		} elseif ($belongs == BELONGS_BULK_INVOICES) {
			$dirname = 'data/files/order/bulk/' .date('Ym');
			$upload_file_id = 'sample_sourcing';
		}elseif ($belongs == BELONGS_CONSUMER_COMMENT_ORDER){
			$dirname = 'data/files/order/consumer/' .date('Ym');
			$upload_file_id = 'file_consumer_comment';
		} elseif ($belongs == BELONGS_CONSUMER_REMARKS_ORDER){
			$dirname = 'data/files/order/consumer/' .date('Ym');
			$upload_file_id = 'file_consumer_remarks';
		} elseif ($belongs == BELONGS_QUOTE_ORDER){
			$dirname = 'data/files/order/quote/' .date('Ym');
			$upload_file_id = 'quote_order_file';
		} elseif ($belongs == BELONGS_SAMPLE_THUMB_IMG){
			$dirname='data/files/sample/thumb/' .date('Ym');
			$upload_file_id='sample_thumb_img';
		} elseif ($belongs == BELONGS_RECEIPT_ORDER){
			$dirname='data/files/order/receipt/' .date('Ym');
			$upload_file_id='receipt_order_file';
		}elseif ($belongs == BELONGS_QUOTE_CONTRACT){
			$dirname = 'data/files/order/quote/contract/' .date('Ym');
			$upload_file_id = 'quote_contract_file';
		}elseif ($belongs == BELONGS_CUT_ORDER){
			$dirname = 'data/files/order/cut/' .date('Ym');
			$upload_file_id = 'cut_order_file';
		}elseif ($belongs == BELONGS_FABRIC_INFO){
			$dirname = 'data/files/sample/fabric/' .date('Ym');
			$upload_file_id = 'fabric_info_file';
		}elseif ($belongs == BELONGS_SAMPLE_PATTERN){
			$dirname = 'data/files/sample/pattern/' .date('Ym');
			$upload_file_id = 'sample_pattern_file';
		}elseif ($belongs == BELONGS_PROCESS_RECEIPT){
			$dirname = 'data/files/order/process/' .date('Ym');
			$upload_file_id = 'process_receipt_file';
		}elseif ($belongs==BELONGS_MAIN_LABEL){
			$dirname = 'data/files/order/main/' .date('Ym');
			$upload_file_id = 'main_label_file';
		}elseif ($belongs==BELONGS_QUOTE_DETAIL){
			$dirname = 'data/files/order/quote/info/' .date('Ym');
			$upload_file_id = 'factory_quote_info';
		}elseif ($belongs==BELONGS_QUOTE_THUM_IMG){
			$dirname = 'data/files/order/quote/thumb/' .date('Ym');
			$upload_file_id = 'quote_thumb_img';
		}elseif ($belongs==BELONGS_SAMPLE_QUOTE_DETAIL){
			$dirname = 'data/files/sample/quote/info/' .date('Ym');
			$upload_file_id = 'factory_quote_info';
		}elseif ($belongs==BELONGS_SAMPLE_QUOTE_THUM_IMG){
			$dirname = 'data/files/sample/quote/thumb/' .date('Ym');
			$upload_file_id = 'quote_thumb_img';
		}elseif ($belongs==BELONGS_NEWS){
			$dirname = 'data/files/news/' .date('Ym');
			$upload_file_id = 'news_images';
		}elseif ($belongs==BELONGS_LISTING_IMG){
			$dirname = 'data/files/order/listing/' .date('Ym');
			$upload_file_id = 'listing_img';
		}elseif ($belongs==BELONGS_STATEMENT_FILE){
			$dirname = 'data/files/order/statement/' .date('Ym');
			$upload_file_id = 'statement_file_'.$id;
		}elseif ($belongs==BELONGS_MEMBER_IMG){
			$dirname = 'data/files/member/' .date('Ym');
			$upload_file_id = 'member_beautiful_img';
		}elseif ($belongs==BELONGS_ORDER_THUMB_IMG){
			$dirname = 'data/files/order/thumb/' .date('Ym');
			$upload_file_id = 'order_thumb_image';
		}elseif ($belongs==BELONGS_CONSUMER_SCHEDULE){
			$dirname = 'data/files/consumer/schedule/' .date('Ym');
			$upload_file_id = 'consumer_schedule_file';
		}elseif ($belongs==BELONGS_SAMPLE_REF_IMG){
			$dirname = 'data/files/sample/ref/' .date('Ym');
			$upload_file_id = 'ref_img';
		}elseif ($belongs==BELONGS_SAMPLE_RECOMM_COLOR){
			$dirname = 'data/files/sample/recomm/' .date('Ym');
			$upload_file_id = 'demand_recomm_file';
		}elseif ($belongs==BELONGS_ORDER_REF_IMG){
			$dirname = 'data/files/order/ref/' .date('Ym');
			$upload_file_id = 'ref_img';
		}elseif ($belongs==BELONGS_ORDER_RECOMM_COLOR){
			$dirname = 'data/files/order/recomm/' .date('Ym');
			$upload_file_id = 'demand_recomm_file';
		}elseif ($belongs==BELONGS_SS_WATER_IMG){
			$dirname='data/files/order/ss/water/'.date('Ym');
			$upload_file_id='ss_water_img';
		}
		else{
			$dirname = 'data/files/order/' .date('Ym');
			$upload_file_id = 'order_attachment';
		}
		
        import('uploader.lib'); // 导入上传类
        import('image.func');
        $uploader = new Uploader();
        $uploader->allowed_type(DOC_FILE_TYPE); // 限制文件类型
        $uploader->allowed_size(SIZE_DOC); // 限制单个文件大小2M

        $uploader->addFile($file);

        if (!$uploader->file_info())
        {
            $this->json_error($uploader->get_error());
            exit();
        }
			
        /* 指定保存位置的根目录 */
        $uploader->root_dir(ROOT_PATH);
        $filename  = $uploader->random_filename();
        /* 上传 */
        $file_path = $uploader->save($dirname, $filename); // 保存到指定目录
        if (!$file_path)
        {
            $this->json_error('file_save_error');
            exit();
        }

		/* 将文件信息写入数据库 */
		$upload_mod =& m('upload');
		$data = array(
			'file_name' => $file['name'],
			'file_path' => $file_path,
			'file_type' => $belongs,
			'key_id' => $id,
			'session_id'=>session_id()
		);
		if ($this->visitor->get('role')==USER_MERCHANT){
			$data['merch_id']=$this->visitor->get('user_id');
		}
		$file_id = $upload_mod->add($data);
		
        if (!$file_id)
        {
            $this->json_error('file_add_error');
            exit();
        }

        /* 返回客户端 */
        $ret_info = array_merge($ret_info, array(
			'file_name' => $file['name'],
			'file_id'   => $file_id,
            'file_path' => $file_path,
        	'key_id'	=> $id,
			'upload_file_id'=>$upload_file_id,
        	'session_id' => session_id() 
        ));
        $this->json_result($ret_info);
		
    }	
	
	
	function sample_pics_upload()
	{
		
		$upload_type = empty($_GET['upload_type']) ? "" : trim($_GET['upload_type']);
		$id = empty($_GET['id']) ? 0 : intval($_GET['id']);

		if (!$upload_type) {
			$this->json_error(Lang::get('system_error'));
            exit();
		}
		
		$dirname = $id ? 'data/files/sample/' . $id : 'data/files/sample/temp';
		
        $ret_info = array(); // 返回到客户端的信息
        $file = $_FILES['Filedata'];
        if ($file['error'] == UPLOAD_ERR_NO_FILE) // 没有文件被上传
        {
            $this->json_error('no_upload_file');
            exit();
        }
		
        import('uploader.lib'); // 导入上传类
        import('image.func');
        $uploader = new Uploader();
        $uploader->allowed_type(DOC_FILE_TYPE); // 限制文件类型
        $uploader->allowed_size(SIZE_DOC); // 限制单个文件大小2M

        $uploader->addFile($file);

        if (!$uploader->file_info())
        {
            $this->json_error($uploader->get_error());
            exit();
        }
			
        /* 指定保存位置的根目录 */
        $uploader->root_dir(ROOT_PATH);
        $filename  = $uploader->random_filename();
        /* 上传 */
        $file_path = $uploader->save($dirname, $filename); // 保存到指定目录
        if (!$file_path)
        {
            $this->json_error('file_save_error');
            exit();
        }
		import('image.func');
		$front_pic_small_path = $dirname . '/small_' . basename($file_path);
        make_thumb(ROOT_PATH . '/' . $file_path, ROOT_PATH .'/' . $front_pic_small_path, THUMB_WIDTH, THUMB_HEIGHT, THUMB_QUALITY);
        /* 返回客户端 */
        $ret_info = array_merge($ret_info, array(
			'file_name' => $file['name'],
            'file_path' => $file_path,
			'upload_type'=>$upload_type,
			'front_pic_small'=>$front_pic_small_path
        ));
        $this->json_result($ret_info);
	}
	
	function order_pics_upload()
	{
		
		$upload_type = empty($_GET['upload_type']) ? "" : trim($_GET['upload_type']);
		$id = empty($_GET['id']) ? 0 : intval($_GET['id']);

		if (!$upload_type) {
			$this->json_error(Lang::get('system_error'));
            exit();
		}
		
		 $dirname = $id ? 'data/files/order/' .date('Ym') : 'data/files/order/temp';
		
        $ret_info = array(); // 返回到客户端的信息
        $file = $_FILES['Filedata'];
        if ($file['error'] == UPLOAD_ERR_NO_FILE) // 没有文件被上传
        {
            $this->json_error('no_upload_file');
            exit();
        }
		
        import('uploader.lib'); // 导入上传类
        import('image.func');
        $uploader = new Uploader();
        $uploader->allowed_type(DOC_FILE_TYPE); // 限制文件类型
        $uploader->allowed_size(SIZE_DOC); // 限制单个文件大小2M

        $uploader->addFile($file);

        if (!$uploader->file_info())
        {
            $this->json_error($uploader->get_error());
            exit();
        }
			
        /* 指定保存位置的根目录 */
        $uploader->root_dir(ROOT_PATH);
        $filename  = $uploader->random_filename();
        /* 上传 */
        $file_path = $uploader->save($dirname, $filename); // 保存到指定目录
        if (!$file_path)
        {
            $this->json_error('file_save_error');
            exit();
        }

        /* 返回客户端 */
        $ret_info = array_merge($ret_info, array(
			'file_name' => $file['name'],
            'file_path' => $file_path,
			'upload_type'=>$upload_type
        ));
        $this->json_result($ret_info);
	}
}
?>